package alogrithm.bigdata.phonenumbersort;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.BitSet;

public class BigPhoneNumberSorter {
	private int defaultSize=1<<32;
	BitSet bs=new BitSet(defaultSize);
	
	public void sort(String orgName,String targetName)throws Exception{
		BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(orgName)));
		String line=null;
		while((line=reader.readLine())!=null){
			bs.set(Integer.valueOf(line), true);
		}
		reader.close();
		
		BufferedWriter writer=new BufferedWriter(new FileWriter(new File(targetName)));
		int c=0;
		for(int i=0;i<bs.size();i++,c++){
			if(bs.get(i)){
				writer.append(String.valueOf(i));
				writer.append("\n");
				
				if(c%1024*1024==0){
					writer.flush();
				}
			}
		}
		writer.flush();
		writer.close();
	}
	
	public static void main(String[] args) throws Exception{
		new BigPhoneNumberSorter().sort("c:/phone.txt", "c:/phone-sorted.txt");
	}
}
